var zNodes = null, zTree_Menu = null, gridData = null;
var rootPath = getRootPath();
var currentMenuId = 0, currentGridURL = rootPath + "/menu/getMenuByMenuId.json", page = 1, currentrp = 20;
var grid;
var selectNodes;
var setting = {
    view: {
        showLine: true,
        selectedMulti: false
    },
    callback: {
        onClick: function(e, treeId, node){
            currentGridURL = rootPath + "/menu/getMenuByMenuId.json";
            page = 1;
            selectNodes = node.menu_id;
            getGrid({
                page: page,
                rp: currentrp,
                menu_id: node.menu_id
            }, currentGridURL);
        }
    }
};
var optionsGray = {
    position: {
        x: 'right',
        y: 'top'
    },
    offset: {
        x: -100,
        y: 0
    },
    template: '<div class="{errMsgClass}">{message}</div>',
    validateOn: 'blur'
};
var menu_colomns = [{
    display: 'ISO',
    name: 'ids',
    width: 30,
    align: 'center'
}, {
    display: '菜单名称',
    name: 'menu_name',
    width: 180,
    align: 'center'
}, {
    display: 'URL',
    name: 'menu_url',
    width: 180,
    align: 'center'
}, {
    display: '图标',
    name: 'menu_icon',
    width: 180,
    align: 'center'
}, {
    display: '类型',
    name: 'menu_type',
    width: 60,
    align: 'center',
    format: function(data, item){
        switch (item) {
            case 0:
                return "页面";
            case 1:
                return "操作";
            case 2:
                return "普通节点";
        }
    }
}, {
    display: '父节点',
    name: 'menu_parent',
    width: 60,
    align: 'center',
    format: function(data, item){
        var rootName = "Root";
        $.each(gridData.rows, function(index, items){
            if (items.menu_id == item) {
                rootName = items.menu_name;
            }
        });
        return rootName;
    }
}, {
    display: '是否子节点',
    name: 'isleaf',
    width: 60,
    align: 'center',
    format: function(data, item){
        return item == "1" ? "是" : "否";
    }
}, {
    display: '是否系统默认',
    name: 'issys',
    width: 60,
    align: 'center',
    format: function(data, item){
        switch (item) {
            case -1:
                return "系统内置";
            case 1:
                return "系统默认";
            case 0:
                return "非系统默认";
        }
    }
}, {
    display: '是否可见',
    name: 'isvisiable',
    width: 60,
    align: 'center',
    format: function(data, item){
        return item == "1" ? "是" : "否";
    }
}, {
    display: '是否关联',
    name: 'menu_rel',
    width: 60,
    align: 'center',
    format: function(data, item){
        return item == "1" ? "是" : "否";
    }
}, {
    display: '描述',
    name: 'memo',
    width: 120,
    align: 'center'
}];
var menu_buttons = [{
    name: '添加',
    bclass: 'add',
    onpress: function(){
        $("#dialog-form").attr("title", "添加菜单");
        $("#dialog-form").dialog("option", "buttons", [{
            text: "添加菜单",
            click: function(){
                addmenu(zTree_Menu);
            }
        }, {
            text: "取消",
            click: function(){
                $(this).dialog("close");
            }
        }])
        $("#dialog-form").dialog("open");
    }
}, {
    name: '修改',
    bclass: 'update',
    onpress: function(){
        var menu_id;
        var checkboxs = $("#menu_table input:checkbox[checked]");
        if (checkboxs.length == 0) {
            showMsg("请选择一项!", true, "错误信息", false);
        }
        else 
            if (checkboxs.length > 1) {
                showMsg("不能选择多项!", true, "错误信息", false);
            }
            else {
                menu_id = checkboxs.val();
                showMsg("正在获取......", false, "获取信息", true);
                $.ajax({
                    type: "POST",
                    url: rootPath + "/menu/selectMenu.json",
                    dataType: "json",
                    data: {
                        menu_id: menu_id
                    },
                    cache: false,
                    async: true,
                    error: function(xhr, ts, et){
                        var statusError = xhr.status
                        if (statusError == 403) {
                            showMsg("没有权限!", true, "错误信息", false);
                        }
                        else 
                            if (statusError == 500) {
                                showMsg("系统内置错误!", true, "错误信息", false);
                            }
                            else {
                                showMsg("未知错误!", true, "错误信息", false);
                            }
                    },
                    success: function(msg){
                        if (msg.failtrue) {
                            showMsg(msg.msg, true, "错误信息", false);
                            $("#dialog-form").dialog("close");
                        }
                        else {
                            $("#menu_message").dialog("close");
                            $("#menu_name").val(msg.menu_name);
                            $("#menu_url").val(msg.menu_url);
                            $("#menu_parent").val(msg.menu_parent);
                            $("menu_icon").val(msg.menu_icon);
                            $("#isleaf").attr("checked", msg.isleaf == 1 ? true : false);
                            $("#isvisiable").attr("checked", msg.isvisiable == 1 ? true : false);
                            $("#issys").attr("checked", msg.issys == 1 ? true : false);
                            $("#menu_rel").attr("checked", msg.menu_rel == 1 ? true : false);
                            $("#menu_type").val(msg.menu_type);
                            $("#memo").val(msg.memo);
                            if (msg.menu_type == 1) {
                                $("#menu_rel").attr("disabled", false);
                            }
                            $("#dialog-form").attr("title", "修改菜单");
                            $("#dialog-form").dialog("option", "buttons", [{
                                text: "修改菜单",
                                click: function(){
                                    updatemenu(zTree_Menu, menu_id);
                                }
                            }, {
                                text: "取消",
                                click: function(){
                                    $(this).dialog("close");
                                }
                            }]);
                            $("#dialog-form").dialog("open");
                        }
                    }
                });
            }
    }
}, {
    name: '删除',
    bclass: 'delete',
    onpress: function(){
        var checkboxs = $("#menu_table input:checkbox[checked]");
        if (checkboxs.length == 0) {
            showMsg("请至少选择一项!", true, "错误信息", false);
        }
        else {
            deletemenu(checkboxs);
        }
    }
}, {
    name: '查询',
    bclass: 'find',
    onpress: function(){
        findmenu();
    }
}, {
    separator: true
}];
$(document).ready(function(){
    $('body').layout({
        defaults: {
            resizerClass: "resizer",
            togglerClass: "toggler",
            buttonClass: "button",
            togglerLength_open: 25,
            togglerLength_closed: 25,
			onresize_end: function(){
				var zwidth=$('.ztree').width();
				$(document).find('div.grid').width(document.documentElement.clientWidth-zwidth-25);
			}
        },
        west: {
            resizable: true,
            slidable: false,
            closable: false
        }
    });
    getTree();
    grid = $("#menu_table").flexigrid({
        dataType: 'json',
        colModel: menu_colomns,
        buttons: menu_buttons,
        sortname: "iso",
        sortorder: "asc",
        usepager: true,
        checkbox: true,
        nowrap: false,
        title: '菜单管理',
        page: 1,
        total: 1,
        useRp: true,
        rp: currentrp,
        rpOptions: [5, 10, 15, 20, 25, 30, 40],
        resizable: false,
        width: document.documentElement.clientWidth - 210,
        height: document.documentElement.clientHeight - 115,
        pagestat: '显示记录从{from}到{to}，总数 {total} 条',
        procmsg: '正在加载数据,请稍等...',
        nomsg: '没有符合条件的记录存在',
        errormsg: '发生错误',
        autoload: false,
        onChangePage: function(newp){
            if (!newp) {
                return false;
            }
            else {
                getGrid({
                    page: newp,
                    rp: currentrp,
                    menu_id: selectNodes
                }, currentGridURL);
            }
        },
        onRpChange: function(rp){
            currentrp = rp;
            getGrid({
                page: 1,
                rp: currentrp,
                menu_id: selectNodes
            }, currentGridURL);
        },
        onReload: function(page){
            getGrid({
                page: page,
                rp: currentrp,
                menu_id: selectNodes
            }, currentGridURL);
        }
    });
    var data = {
        page: 1,
        rp: currentrp
    };
    getGrid(data, currentGridURL, true);
    $("#menu_form").bValidator(optionsGray);
    $("#dialog-form").dialog({
        autoOpen: false,
        height: 370,
        width: 500,
        modal: true,
        resizable: false,
        closeOnEscape: false,
        close: function(){
            $("#dialog-form input[type=text]").val("");
            $("#dialog-form input[type=checkbox]").attr("checked", false);
            $("#dialog-form textarea").val("");
        }
    });
    $("#find-form").dialog({
        autoOpen: false,
        height: 230,
        width: 450,
        modal: true,
        resizable: false,
        closeOnEscape: false
    });
    $("a.ui-dialog-titlebar-close").attr("href", "javascript:void(0);");
    $("#menu_parent").append("<option value='0'>Root</option>");
    $("#_menu_parent").append("<option value=''>请选择</option><option value='0'>Root</option>");
    $.each(gridData.rows, function(index, items){
        if ((items.isleaf == 0 && items.menu_type != 1) || (items.isleaf == 1 && items.menu_type == 0)) {
            $("#menu_parent").append("<option value='" + items.menu_id + "'>" + items.menu_name + "</option>");
            $("#_menu_parent").append("<option value='" + items.menu_id + "'>" + items.menu_name + "</option>");
        }
    });
    $("#menu_type").live("change", function(){
        if ($("#menu_type").val() == 1) {
            $("#menu_rel").attr("disabled", false);
        }
        else {
            $("#menu_rel").attr("disabled", true);
        }
    });
});
function getRootPath(){
    var strFullPath = window.document.location.href;
    var strPath = window.document.location.pathname;
    var pos = strFullPath.indexOf(strPath);
    var prePath = strFullPath.substring(0, pos);
    var postPath = strPath.substring(0, strPath.substr(1).indexOf('/') + 1);
    return (prePath + postPath);
}

function addmenu(zTree_Menu){
    showMsg("正在添加......", false, "添加菜单", true);
    var menu_name = $("#menu_name").val();
    var menu_url = $("#menu_url").val();
    var menu_parent = $("#menu_parent").val();
    var menu_icon = $("menu_icon").val();
    var isleaf = $("#isleaf").attr("checked") == "checked" ? "1" : "0";
    var isvisiable = $("#isvisiable").attr("checked") == "checked" ? "1" : "0";
    var issys = $("#issys").attr("checked") == "checked" ? "1" : "0";
    var isrel = $("#menu_rel").attr("checked") == "checked" ? "1" : "0";
    var menu_type = $("#menu_type").val();
    var memo = $("#memo").val();
    $.ajax({
        type: "POST",
        url: rootPath + "/menu/addMenu.json",
        dataType: "json",
        data: {
            menu_name: menu_name,
            menu_url: menu_url,
            menu_parent: menu_parent,
            menu_icon: menu_icon,
            isleaf: isleaf,
            isvisiable: isvisiable,
            issys: issys,
            isrel: isrel,
            menu_type: menu_type,
            memo: memo
        },
        cache: false,
        async: false,
        error: function(xhr, ts, et){
            var statusError = xhr.status
            if (statusError == 403) {
                showMsg("没有权限!", true, "错误信息", false);
            }
            else 
                if (statusError == 500) {
                    showMsg("系统内置错误!", true, "错误信息", false);
                }
                else {
                    showMsg("未知错误!", true, "错误信息", false);
                }
        },
        success: function(msg){
            alert(msg);
            if (msg.success) {
                $("#dialog-form").dialog("close");
                showMsg(msg.msg, true, "验证信息", false);
                getTree();
                getGrid({
                    page: 1,
                    rp: currentrp
                }, rootPath + "/menu/getMenuByMenuId.json");
                window.parent.getMainTree();
            }
            else 
                if (msg.failtrue) {
                    showMsg(msg.msg, true, "错误信息", false);
                }
        }
    });
}

function updatemenu(zTree_Menu, menu_id){
    showMsg("正在更新......", false, "更新菜单", true);
    var menu_name = $("#menu_name").val();
    var menu_url = $("#menu_url").val();
    var menu_parent = $("#menu_parent").val();
    var menu_icon = $("menu_icon").val();
    var isleaf = $("#isleaf").attr("checked") == "checked" ? "1" : "0";
    var isvisiable = $("#isvisiable").attr("checked") == "checked" ? "1" : "0";
    var issys = $("#issys").attr("checked") == "checked" ? "1" : "0";
    var isrel = $("#menu_rel").attr("checked") == "checked" ? "1" : "0";
    var menu_type = $("#menu_type").val();
    var memo = $("#memo").val();
    $.ajax({
        type: "POST",
        url: rootPath + "/menu/updateMenu.json",
        dataType: "json",
        data: {
            menu_id: menu_id,
            menu_name: menu_name,
            menu_url: menu_url,
            menu_parent: menu_parent,
            menu_icon: menu_icon,
            isleaf: isleaf,
            isvisiable: isvisiable,
            issys: issys,
            isrel: isrel,
            menu_type: menu_type,
            memo: memo
        },
        cache: false,
        async: false,
        error: function(xhr, ts, et){
            var statusError = xhr.status
            if (statusError == 403) {
                showMsg("没有权限!", true, "错误信息", false);
            }
            else 
                if (statusError == 500) {
                    showMsg("系统内置错误!", true, "错误信息", false);
                }
                else {
                    showMsg("未知错误!", true, "错误信息", false);
                }
        },
        success: function(msg){
            if (msg.success) {
                $("#dialog-form").dialog("close");
                showMsg(msg.msg, true, "验证信息", false);
                getTree();
                getGrid({
                    page: 1,
                    rp: currentrp
                }, rootPath + "/menu/getMenuByMenuId.json");
                window.parent.getMainTree();
            }
            else 
                if (msg.failtrue) {
                    showMsg(msg.msg, true, "错误信息", false);
                }
        }
    });
}

function deletemenu(checkboxs){
    var menu_ids;
    $.each(checkboxs, function(index, items){
        menu_ids = checkboxs.val() + ",";
    });
    showMsg("确定要删除?(<font color='red'>子节点也会相应删除!</font>)", false, "删除菜单", false);
    $("#menu_message").dialog("option", "buttons", [{
        text: "确定删除",
        click: function(){
            $("#menu_message").dialog("destroy");
            showMsg("删除中......", false, "执行信息", true);
            $.ajax({
                type: "POST",
                url: rootPath + "/menu/deleteMenu.json",
                dataType: "json",
                data: {
                    menu_ids: menu_ids
                },
                cache: false,
                async: false,
                error: function(xhr, ts, et){
                    var statusError = xhr.status
                    if (statusError == 403) {
                        showMsg("没有权限!", true, "错误信息", false);
                    }
                    else 
                        if (statusError == 500) {
                            showMsg("系统内置错误!", true, "错误信息", false);
                        }
                        else {
                            showMsg("未知错误!", true, "错误信息", false);
                        }
                },
                success: function(msg){
                    if (msg.failture) {
                        showMsg(msg.msg, true, "错误信息", false);
                    }
                    else {
                        showMsg(msg.msg, true, "执行信息", false);
                        getTree();
                        getGrid({
                            page: 1,
                            rp: currentrp
                        }, rootPath + "/menu/getMenuByMenuId.json");
                        window.parent.getMainTree();
                    }
                }
            });
        }
    }, {
        text: "取消",
        click: function(){
            $(this).dialog("close");
            $(this).dialog("destroy");
        }
    }]);
}

function findmenu(){
    currentGridURL = rootPath + "/menu/findMenus.json";
    $("#find-form").dialog("open");
    $("#find-form").dialog("option", "buttons", [{
        text: "查询",
        click: function(){
            showMsg("正在查询......", false, "执行信息", true);
            var menu_name = $("#_menu_name").val();
            var menu_parent = $("#_menu_parent").val();
            var isleaf = $("#_isleaf").val();
            var isvisiable = $("#_isvisiable").val();
            var menu_rel = $("#_menu_rel").val();
            var menu_type = $("#_menu_type").val();
            data = {
                page: 1,
                rp: currentrp,
                menu_name: menu_name,
                menu_parent: menu_parent,
                isleaf: isleaf,
                isvisiable: isvisiable,
                isrel: menu_rel,
                menu_type: menu_type
            }
            getGrid(data, currentGridURL);
            $("#find-form").dialog("close");
            $("#menu_message").dialog("close");
            $("#menu_message").dialog("destroy");
        }
    }, {
        text: "清空",
        click: function(){
            $("#find-form input").val('');
            $("#find-form select").val('');
        }
    }, {
        text: "关闭",
        click: function(){
            $("#find-form").dialog("close");
        }
    }]);
}

function getGrid(data, url, flag){
    $.ajax({
        type: "POST",
        url: url,
        dataType: "json",
        data: data,
        cache: false,
        async: false,
        error: function(xhr, ts, et){
            var statusError = xhr.status
            if (statusError == 403) {
                showMsg("没有权限!", true, "错误信息", false);
            }
            else 
                if (statusError == 500) {
                    showMsg("系统内置错误!", true, "错误信息", false);
                }
                else {
                    showMsg("未知错误!", true, "错误信息", false);
                }
        },
        success: function(msg){
            if (msg.failture) {
                showMsg(msg.msg, true, "错误信息", false);
            }
            else {
                if (flag) {
                    gridData = msg;
                }
                grid.flexOptions({
                    rp: data.rp
                });
                grid.flexAddData(msg);
            }
        }
    });
}

function getTree(){
    $.ajax({
        type: "POST",
        url: rootPath + "/menu/getAllMenuTree.json",
        dataType: "json",
        cache: false,
        async: false,
        error: function(xhr, ts, et){
            var statusError = xhr.status
            if (statusError == 403) {
                showMsg("没有权限!", true, "错误信息", false);
            }
            else 
                if (statusError == 500) {
                    showMsg("系统内置错误!", true, "错误信息", false);
                }
                else {
                    showMsg("未知错误!", true, "错误信息", false);
                }
        },
        success: function(msg){
            if (msg.failture) {
                showMsg(msg.msg, true, "错误信息", false);
            }
            else {
                zNodes = msg.msg;
            }
        }
    });
    $.fn.zTree.init($("#menu_tree"), setting, zNodes);
    zTree_Menu = $.fn.zTree.getZTreeObj("menu_tree");
}

function showMsg(msg, isbutton, title, hideicon){
    $("#menu_message").attr("title", title);
    $("#menu_message p").attr("align", "center").css("padding", "1em").addClass("ui-state-highlight ui-corner-all").html(msg);
    $("#menu_message").dialog({
        autoOpen: true,
        modal: true,
        resizable: false,
        closeOnEscape: false,
        open: function(event, ui){
            if (hideicon) {
                $("#menu_message").prev().first().find(".ui-dialog-titlebar-close").hide();
            }
        }
    });
    if (isbutton) {
        $("#menu_message").dialog("option", "buttons", [{
            text: "确定",
            click: function(){
                $(this).dialog("close");
                $(this).dialog("destroy");
            }
        }]);
    }
}
